<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border fit size="small">
        <el-table-column align="center" label="母品牌" width="120">
          <template slot-scope="scope">
            <el-input v-if="!scope.row.is_edit&&!scope.row.is_add" size="small" disabled :value="scope.row.org_name">
            </el-input>
            <el-select v-else size="small" :disabled="!scope.row.is_edit&&!scope.row.is_add" v-model="scope.row.org_id"
              @change="getSecond(scope.row.org_id,scope.$index)">
              <el-option v-for="item in brand_first_list" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="子品牌" width="120">
          <template slot-scope="scope">
            <el-input v-if="!scope.row.is_edit&&!scope.row.is_add" size="small" disabled :value="scope.row.brand_name">
            </el-input>
            <el-select v-else size="small" :disabled="!scope.row.is_edit&&!scope.row.is_add" v-model="scope.row.brand_id"
              @change="getStore(scope.row.brand_id,scope.$index,false)" filterable>
              <el-option v-for="item in brand_second_list" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="门店" width="200">
          <template slot-scope="scope">
            <el-input v-if="!scope.row.is_edit&&!scope.row.is_add" size="small" disabled :value="scope.row.store_name">
            </el-input>
            <el-select v-else size="small" :disabled="!scope.row.is_edit&&!scope.row.is_add" v-model="scope.row.store_id" filterable>
              <el-option v-for="item in store_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="权限组" prop="size">
          <template slot-scope="scope">
            <el-tag style="margin: 2px;" v-for="(item,index) in scope.row.group" :disable-transitions="true" :key="index"
              :closable="scope.row.is_edit||scope.row.is_add" @close="delGroup(scope.row.group,index)">
              <span style="cursor:pointer" @click="onAuthgroupEditClick(item.group_id)">{{item.name}}</span>
            </el-tag>
            <el-button size="mini" v-if="scope.row.is_edit||scope.row.is_add" type="text" @click="groupDialogShow(scope.$index)">
              <i class="el-icon-circle-plus-outline"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="160">
          <template slot-scope="scope">
            <span v-if="!scope.row.is_add">
              <el-button v-if="!scope.row.is_edit" type="primary" icon="el-icon-edit" size="mini" @click="editClick(scope.$index,scope.row)"></el-button>
              <el-button v-if="scope.row.is_edit" type="success" size="mini" @click="saveGroupClick(scope.row)">保存
              </el-button>
              <el-button v-show="scope.row.is_edit" size="mini" @click="scope.row.is_edit = false">取消
              </el-button>
              <el-button v-if="!scope.row.is_edit" type="danger" icon="el-icon-delete" size="mini" @click="delClick(scope.row.id,scope.$index)">
              </el-button>
            </span>
            <el-button v-if="scope.row.is_add" type="primary" size="mini" @click="saveGroupClick(scope.row)">新增
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分配权限组 -->
    <el-dialog :close-on-click-modal="false" class="dialog_table" width="65%" title="分配权限组" :visible.sync="groupDialog" append-to-body>
      <div style="position:relative;bottom:20px;text-align: center">
        <el-input placeholder="搜索分组" class="w160" size="small" v-model="groupName" @keyup.enter.native="getGroup">
        </el-input>&#x3000;
        <el-button type="primary" size="small" @click="getGroup">搜索</el-button>
      </div>
      <el-table highlight-current-row style="height: 60vh;overflow:auto;" ref="groupList" :data="groupList" v-loading.body="listLoading"
        element-loading-text="Loading" border fit size="small">
        <el-table-column align="center" label="权限组名称" prop="name"></el-table-column>
        <el-table-column align="center" label="描述" prop="intro"></el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="addGroupClick(scope.row.id,scope.row.name)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 自定义底部 -->
      <div class="bottom_box">
        <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
          layout="prev, pager, next, jumper" :total="totalDataNumber">
        </el-pagination>
        <el-button class="pull-right" type="primary" size="small" @click="onAuthgroupAddClick">新增权限组</el-button>
      </div>
    </el-dialog>
    <!-- 权限组编辑&新增权限组弹框 权限维护 -->
    <el-dialog :close-on-click-modal="false" class="dialog_table" width="80%" title="权限维护" :visible.sync="authDialog" @close="closeDialog">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item label="分组名称" style="width: 40%;">
          <el-input :disabled="isDisabled" v-model="saveForm.name" placeholder="分组名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" style="width: 50%;">
          <el-input :disabled="isDisabled" type="textarea" v-model="saveForm.intro" placeholder="描述" style="width:300px"></el-input>
        </el-form-item>
      </el-form>
      <!-- 权限分类单项切换 -->
      <el-radio-group v-model="authTypeRadio" @change="onAuthTypeRadioChanged">
        <el-radio label="pc">PC</el-radio>
        <el-radio label="web">Web</el-radio>
        <el-radio label="app">App</el-radio>
      </el-radio-group>
      <br />
      <br />
      <!-- 权限tap标签分类 -->
      <el-tabs v-model="authTreeTapName" @tab-click="onAuthTreeTapClick" style="width: 100%">
        <el-tab-pane v-for="(itemtop, idxtop) in authtaps" :id="itemtop.id" :key="idxtop" :label="itemtop.name" :name="itemtop.name"></el-tab-pane>
      </el-tabs>
      <!-- 通过table合并某些行，绘制权限树 -->
      <el-table highlight-current-row :data="tableData" :span-method="objectSpanMethod" border :show-header="false" size="mini" style="width: 100%">
        <el-table-column v-for="(item, idx) in columnList" :key="idx">
          <template slot-scope="scope">
            <!-- checkbox表示具体的权限，可以选中或取消权限 -->
            <el-checkbox :disabled="isDisabled" @change="ckchanged(tableData,scope.$index,item)" v-model="tableData[scope.$index][item].status" size="mini">
              {{tableData[scope.$index][item].name}}
            </el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!-- 权限组编辑或新增保存按钮 -->
        <el-button v-if="!isDisabled" type="primary" @click="saveClick()" size="small">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getPage, brand_first_list, brand_second_list, store_list, groupList, groupPage, editAuthGroup, del } from '@/api/setting/auth_user_store';
import { getAuthgoupInfo, saveAuthgroup, addAuthgroup, delAuthgroup, getUserList } from '@/api/setting/auth_manager';
export default {
  data() {
    return {
      isDisabled: true,
      groupDialog: false,
      addGroupIndex: '',
      list: null,
      listLoading: false,
      brand_first_list: [],
      brand_second_list: [],
      store_list: [],
      groupList: [], //弹框权限组列表
      groupName: '',
      authTreeTapName: '', //指示当前权限树Tap标签
      authTypeRadio: 'pc', //指示当前权限分类单选选中
      userList: [], //权限用户列表
      authDialog: false, //指示权限组编辑&新增权限组弹框是否弹出展示
      currentPage: 1, //指示当前所在分页
      totalDataNumber: 0,
      saveForm: {
        name: '',
        intro: '',
        auth_id: '' //1,2,3,4,5,70,76,87,244
      },
      formInline: {
        name: ''
      },
      authgroup_id: 0, //指示权限组编辑&新增权限组弹框对应的权限组id，新增权限组时该值为0
      authgroup_initial_name: '', //指示服务器获得的权限组名称，新增权限组时该值为空
      authgroup_initial_intro: '', //指示服务器获得的权限组介绍，新增权限组时该值为空
      auth_initial_flags: [], //指示服务器获得的权限组中权限的选中情况，key为权限id，value为true表示拥有该权限
      auth_modify_flags: [], //指示用户编辑后的权限组中权限的选中情况，key为权限id，value为true表示拥有该权限
      authgoupinfo: [], //指示服务器获得的权限组中所有的权限数据
      authlist: [], //用于临时存储权限分类（pc，web，app）对应的所有选项
      authtaps: [], //权限树Tap标签列表
      colsize: 0, //表示当前权限树的最大深度，及table的列数
      0: this.columnList, //权限树table中的列数据
      1: this.tableData, //权限树绘制数据
      2: this.column_row_offset, //用户生成并绘制权限树table
      6: this.authtreelist //权限树原始数据
    };
  },
  //再界面绘制前定义并初始化相关变量，防止checkbox点击失效
  beforeCreate() {
    this.authtreelist = [];
    this.columnList = [];
    this.tableData = [];
    this.column_row_offset = [];
    for (var ii = 0; ii < 1; ii++) {
      this.columnList[ii] = [];
    }
    for (var i = 0; i < 1; i++) {
      this.tableData[i] = [];
      for (let j = 0; j < 1; j++) {
        this.tableData[i][j] = {};
        this.tableData[i][j].name = '';
        this.tableData[i][j].status = true;
        this.tableData[i][j].id = 0;
        this.tableData[i][j].parent_id = 0;
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      vm.beforeComingIn();
    });
  },
  methods: {
    closeDialog() {
      this.isDisabled = true;
    },
    beforeComingIn() {
      if (this.$route.params.routerflag) {
        this.fetchData();
        this.get_brand_first_list();
        // this.get_brand_second_list();
        // this.get_store_list();
        this.getGroup();
      }
    },
    // 保存权限
    saveGroupClick(data) {
      // console.log(data)
      if (data.group.length == 0) {
        this.$message({ type: 'error', message: '请添加权限组' });
        return;
      }
      if (data.store_id === '') {
        this.$message({
          type: 'error',
          message: '门店信息有误，请重新选择门店'
        });
        return;
      }
      if (data.org_id == 0 && (data.brand_id != 0 || data.store_id != 0)) {
        this.$message({ type: 'error', message: '门店信息有误，请选择品牌' });
        return;
      }
      if (data.brand_id == 0 && data.store_id != 0) {
        this.$message({ type: 'error', message: '门店信息有误，请选择品牌' });
        return;
      }
      let saveForm = {
        clerk_store_id: data.id,
        clerk_id: this.$route.params.clerk_id,
        org_id: data.org_id,
        brand_id: data.brand_id,
        store_id: data.store_id,
        group: []
      };
      data.group.forEach(function(val, index) {
        saveForm.group.push(val.group_id);
      });
      editAuthGroup(saveForm).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        this.fetchData();
      });
    },
    // 删除权限
    delClick(id, index) {
      this.$confirm('此操作删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ clerk_store_id: id }).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    // 删除组标签
    delGroup(data, index) {
      this.$confirm('此操作删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        data.splice(index, 1);
      });
    },
    // 添加
    addGroupClick(group_id, name) {
      let ok = true;
      for (let i = 0; i < this.list[this.addGroupIndex].group.length; i++) {
        if (this.list[this.addGroupIndex].group[i].group_id == group_id) {
          this.$message({ type: 'error', message: '该权限组已存在列表' });
          ok = false;
          break;
        }
      }
      if (ok) {
        this.$message({ type: 'success', message: '添加成功,请保存' });
        this.list[this.addGroupIndex].group.push({
          group_id: group_id,
          name: name
        });
        this.groupDialog = false;
      }
    },
    // 弹框分页
    handleCurrentChange(val) {
      this.listLoading = true;
      groupList({ name: this.groupName, sort: 1 }, val)
        .then(response => {
          this.groupList = response;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 弹框列表
    getGroup() {
      groupPage({ name: this.groupName, sort: 1 }).then(response => {
        this.totalDataNumber = response * 20;
        groupList({ name: this.groupName, sort: 1 }).then(response => {
          this.groupList = response;
        });
      });
    },
    groupDialogShow(index) {
      setTimeout(() => {
        this.$refs['groupList'].doLayout();
      }, 100);
      this.groupDialog = true;
      this.addGroupIndex = index;
    },
    editClick(index, row) {
      this.list[index].is_edit = true;
      //console.log(row)
      this.getSecond(row.org_id, index);
      this.getStore(row.brand_id, index, true);
    },
    getSecond(id, index) {
      this.get_brand_second_list(id);
      // this.list[index].brand_id = '0';
      // this.list[index].store_id = '0';
    },
    getStore(id, index, isEdit) {
      this.get_store_list(id);
      if (!isEdit) {
        this.list[index].store_id = '';
        this.list[index].store_name = '';
      }
    },
    get_brand_first_list() {
      //母品牌
      brand_first_list({ category_id: 95 })
        .then(response => {
          // console.log(response)
          //response[0].id = '0';
          this.brand_first_list = response;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    get_brand_second_list(id) {
      //子品牌
      brand_second_list({ org: id || 1, category_id: 95 })
        .then(response => {
          //console.log(response)
          //response[0].id = '0';
          this.brand_second_list = response;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    get_store_list(id) {
      //门店
      store_list({ brand: id || 0, category_id: 95 })
        .then(response => {
          //console.log(response)
          //response[0].id = '0';
          this.store_list = response;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      getList({ clerk_id: this.$route.params.clerk_id })
        .then(response => {
          for (let i = 0; i < response.length; i++) {
            response[i].is_edit = false;
            response[i].org_name = response[i].org_name == null ? '母品牌' : response[i].org_name;
            response[i].brand_name = response[i].brand_name == null ? '子品牌' : response[i].brand_name;
            response[i].store_name = response[i].store_name == null ? '全门店' : response[i].store_name;
          }
          let last = {
            id: '',
            org_id: '',
            brand_id: '',
            store_id: '',
            group: [],
            is_add: true
          };
          response.push(last);
          this.list = response;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // -------------------查看权限组
    //新增或编辑权限组时，保存按钮点击触发
    saveClick() {
      // console.log(this.auth_initial_flags);
      // console.log(this.auth_modify_flags);
      var addauth = '';
      var delauth = '';
      for (var key in this.auth_modify_flags) {
        if (this.auth_initial_flags[key] != this.auth_modify_flags[key]) {
          // console.log(this.auth_initial_flags[key]);
          if (this.auth_modify_flags[key]) {
            addauth += addauth == '' ? key : ',' + key;
          } else {
            delauth += delauth == '' ? key : ',' + key;
          }
        }
      }

      if (this.authgroup_id == 0) {
        //新增权限组
        //addAuth
        if (this.saveForm.name == '' || this.saveForm.intro == '') {
          this.$message({
            type: 'warning',
            message: '请填写权限组名称和描述'
          });
          return;
        }
        var data = {
          name: this.saveForm.name,
          intro: this.saveForm.intro,
          auth_id: addauth
        };

        addAuthgroup(data).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.authDialog = false;
            this.getGroup();
          }
        });
      } else {
        //修改权限组
        if (this.saveForm.name == this.authgroup_initial_name && this.saveForm.intro == this.authgroup_initial_intro && addauth == '' && delauth == '') {
          this.$message({
            type: 'info',
            message: '没有做任何修改'
          });
          return;
        }

        var data2 = {
          id: this.authgroup_id,
          name: this.saveForm.name,
          intro: this.saveForm.intro,
          auth_add: addauth,
          auth_del: delauth
        };

        saveAuthgroup(data2).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.authDialog = false;
          }
        });
      }
      this.isDisabled = true;
    },
    //删除权限组触发
    onAuthgroupDeleteClick(authgroup_id) {
      this.$confirm('确定删除该权限组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAuthgroup(authgroup_id).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.handleCurrentChange(this.currentPage);
          }
        });
      });
    },
    //编辑权限组按钮点击触发，打开权限组编辑弹框
    onAuthgroupEditClick(authgroup_id) {
      this.authgroup_id = authgroup_id;
      this.authtaps = [];
      this.authlist = [];
      this.auth_initial_flags = [];
      this.auth_modify_flags = [];
      //请求获取权限组数据
      getAuthgoupInfo({ id: this.authgroup_id }).then(response => {
        this.authgoupinfo = response.auth;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          this.authgoupinfo[i].is_view *= 1;
          this.authgoupinfo[i].is_web *= 1;
          this.authgoupinfo[i].parent_id *= 1;
          this.authgoupinfo[i].right *= 1;
          this.auth_initial_flags[this.authgoupinfo[i].id] = this.authgoupinfo[i].right == 1 ? true : false;
          this.authgoupinfo[i].id *= 1;
        }
        // console.log(this.auth_initial_flags);
        this.authgroup_initial_name = response.name;
        this.authgroup_initial_intro = response.intro;
        this.saveForm.name = response.name;
        this.saveForm.intro = response.intro;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          if (this.authgoupinfo[i]['is_web'] == 0) {
            this.authlist.push(this.authgoupinfo[i]);
          }
        }
        for (let i = 0; i < this.authlist.length; i++) {
          if (this.authlist[i]['parent_id'] == 0) {
            this.authtaps.push({
              id: this.authlist[i]['id'],
              name: this.authlist[i]['name']
            });
          }
        }
        //初始化radio，tap选择，生成对应权限树界面
        this.authTypeRadio = 'pc';
        this.authTreeTapName = this.authtaps[0].name;
        this.makeAuthTree(this.authtaps[0].id);
      });
      this.authDialog = true;
    },
    //点击新增权限组按钮触发
    onAuthgroupAddClick() {
      this.isDisabled = false;
      this.authgroup_id = 0; //新增权限组
      this.authtaps = [];
      this.authlist = [];
      this.auth_initial_flags = [];
      this.auth_modify_flags = [];
      //authgroup_id=0表示新增，仅仅获取权限树信息
      getAuthgoupInfo({ id: this.authgroup_id }).then(response => {
        // console.log(response);
        this.authgoupinfo = response.auth;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          this.authgoupinfo[i].is_view *= 1;
          this.authgoupinfo[i].is_web *= 1;
          this.authgoupinfo[i].parent_id *= 1;
          this.authgoupinfo[i].right *= 1;
          this.auth_initial_flags[this.authgoupinfo[i].id] = this.authgoupinfo[i].right == 1 ? true : false;
          this.authgoupinfo[i].id *= 1;
        }
        this.authgroup_initial_name = response.name;
        this.authgroup_initial_intro = response.intro;
        this.saveForm.name = response.name;
        this.saveForm.intro = response.intro;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          if (this.authgoupinfo[i]['is_web'] == 0) {
            this.authlist.push(this.authgoupinfo[i]);
          }
        }
        for (let i = 0; i < this.authlist.length; i++) {
          if (this.authlist[i]['parent_id'] == 0) {
            this.authtaps.push({
              id: this.authlist[i]['id'],
              name: this.authlist[i]['name']
            });
          }
        }
        this.authTypeRadio = 'pc';
        this.authTreeTapName = this.authtaps[0].name;
        this.makeAuthTree(this.authtaps[0].id);
      });
      this.authDialog = true;
    },
    //PC，Web，App分类单选框，单选变化触发，更新权限树界面
    onAuthTypeRadioChanged(value) {
      var type = 0;
      if (value == 'pc') {
        type = 0;
      } else if (value == 'web') {
        type = 1;
      } else if (value == 'app') {
        type = 2;
      } else {
        type = 3;
      }
      this.authtaps = [];
      this.authlist = [];
      for (let i = 0; i < this.authgoupinfo.length; i++) {
        if (this.authgoupinfo[i]['is_web'] == type) {
          this.authlist.push(this.authgoupinfo[i]);
        }
      }
      for (let i = 0; i < this.authlist.length; i++) {
        if (this.authlist[i]['parent_id'] == 0) {
          this.authtaps.push({
            id: this.authlist[i]['id'],
            name: this.authlist[i]['name']
          });
        }
      }
      this.authTreeTapName = this.authtaps[0].name;
      this.makeAuthTree(this.authtaps[0].id);
    },
    //权限树Tap标签被点击，刷新权限树权限
    onAuthTreeTapClick(tab, event) {
      // console.log(tab.$attrs.id);
      this.makeAuthTree(tab.$attrs.id);
    },
    //创建权限树
    makeAuthTree(groupid) {
      this.colsize = 0;
      this.columnList.splice(0);
      this.authtreelist.splice(0);
      // console.log("1111");
      // for (let i = 0; i < this.tableData.length; i++) {
      //   this.tableData[i].pop();
      // }
      this.tableData = [];
      // console.log(this.tableData);

      for (let i = 0; i < this.authgoupinfo.length; i++) {
        if (this.authgoupinfo[i]['id'] == groupid) {
          this.authtreelist.push(this.authgoupinfo[i]);
          this.maketree(this.authgoupinfo[i]['id']);
          break;
        }
      }
      this.column_row_offset.splice(0);

      this.getauthtreeNode(0, 0, 0);
      for (var i = 0; i < this.colsize + 1; i++) {
        this.columnList[i] = '' + i;
      }
    },
    //递归创建权限树，内部方法
    maketree(parent_id) {
      for (let i = 0; i < this.authgoupinfo.length; i++) {
        if (this.authgoupinfo[i]['parent_id'] * 1 == parent_id * 1) {
          // console.log(this.authgoupinfo[i]['parent_id']+" ==== "+parent_id);
          // console.log(this.authgoupinfo[i]);
          this.authtreelist.push(this.authgoupinfo[i]);
          this.maketree(this.authgoupinfo[i]['id']);
        }
      }
    },

    //用户生成权限树table需要的数据格式，主要是tableData数据，计算colsize，column_row_offset等
    getauthtreeNode(parent_id, col, rowidx) {
      var row = 0;
      var tmp_offset = [];
      var tmp = 0;
      // var rowidx = 0;
      for (var i = 0; i < this.authtreelist.length; i++) {
        if (this.authtreelist[i]['parent_id'] * 1 == parent_id) {
          if (this.colsize < col) {
            this.colsize = col;
          }
          if (!this.column_row_offset[col]) {
            this.column_row_offset[col] = [];
          }
          if (tmp > 0) {
            if (this.column_row_offset[col][rowidx]) {
              rowidx += tmp;
              // rowidx += this.column_row_offset[col][rowidx];
            }
          } else {
            if (this.column_row_offset[col][rowidx]) {
              rowidx += 1;
            }
          }
          // console.log(this.authtreelist[i]['id'] + "  " + this.column_row_offset[col][rowidx] + "   " + col + "  " + rowidx);
          tmp = this.getauthtreeNode(this.authtreelist[i]['id'] * 1, col + 1, rowidx);
          // console.log(this.authtreelist[i]['id']+"  "+tmp +"   "+col+"  "+rowidx);

          if (tmp > 0) {
            row += tmp;
            this.column_row_offset[col][rowidx] = tmp;
          } else {
            row += 1;
            tmp = 1;
            this.column_row_offset[col][rowidx] = 1;
          }

          // console.log(this.authtreelist[i]['id'] + "  " + this.column_row_offset[col][rowidx] + "   " + col + "  " + rowidx);
          if (!this.tableData[rowidx]) {
            this.tableData[rowidx] = [];
          }
          for (let k = 0; k < this.column_row_offset[col][rowidx]; k++) {
            if (!this.tableData[rowidx + k][col]) {
              this.tableData[rowidx + k][col] = {};
            }
            if (
              this.auth_modify_flags.hasOwnProperty(this.authtreelist[i].id) &&
              this.auth_modify_flags[this.authtreelist[i].id] != (this.authtreelist[i].right == 1)
            ) {
              this.tableData[rowidx + k].splice(col, 1, {
                id: this.authtreelist[i].id * 1,
                parent_id: this.authtreelist[i].parent_id * 1,
                name: this.authtreelist[i].name,
                status: this.auth_modify_flags[this.authtreelist[i].id]
              });
            } else if (this.authtreelist[i].right == 1) {
              this.tableData[rowidx + k].splice(col, 1, {
                id: this.authtreelist[i].id * 1,
                parent_id: this.authtreelist[i].parent_id * 1,
                name: this.authtreelist[i].name,
                status: true
              });
            } else {
              this.tableData[rowidx + k].splice(col, 1, {
                id: this.authtreelist[i].id * 1,
                parent_id: this.authtreelist[i].parent_id * 1,
                name: this.authtreelist[i].name,
                status: false
              });
            }
          }
        }
      }
      return row;
    },
    //权限树中每个权限有checkbox构成，该方法表示某个权限CheckBox被点击
    ckchanged(data, row, col) {
      if (data[row][col].status) {
        this.auth_modify_flags[data[row][col].id] = true;
        //父节点选中
        this.updateParentStatus(data, data[row][col].parent_id * 1, col * 1 - 1);
      } else if (!data[row][col].status) {
        this.auth_modify_flags[data[row][col].id] = false;
        //子节点取消
        this.updateChildrenStatus(data, data[row][col].id * 1, col * 1 + 1);
      }
    },
    //递归触发子节点取消操作
    updateChildrenStatus(data, parent_id, col) {
      // console.log("col="+col+" parent_id="+parent_id);
      for (var i = 0; i < data.length; i++) {
        // console.log("i="+i+" data.length="+data.length);
        for (var j = col; j < data[i].length; j++) {
          // console.log("i="+i+" j="+j+" status="+data[i][j].status);
          if (data[i][j].parent_id * 1 == parent_id && data[i][j].status) {
            data[i][j].status = false;
            this.auth_modify_flags[data[i][j].id] = false;
            this.updateChildrenStatus(data, data[i][j].id * 1, col * 1 + 1);
          }
        }
      }
    },
    //递归触发父节点选中操作
    updateParentStatus(data, parent_id, col) {
      if (col < 0) return;
      // console.log("col=" + col + " parent_id=" + parent_id);
      for (let i = 0; i < data.length; i++) {
        // console.log("i=" + i + " data.length=" + data.length);
        if (col < data[i].length) {
          for (let j = col; j >= 0; j--) {
            // console.log("i=" + i + " j=" + j + " status="+data[i][j].status);
            if (data[i][j].id * 1 == parent_id && !data[i][j].status) {
              data[i][j].status = true;
              this.auth_modify_flags[data[i][j].id] = true;
              this.updateParentStatus(data, data[i][j].parent_id * 1, col * 1 - 1);
            }
          }
        }
      }
    },
    //权限树绘制，由表格绘制而成，该方法决定表格行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.column_row_offset[columnIndex] && this.column_row_offset[columnIndex][rowIndex]) {
        return {
          rowspan: this.column_row_offset[columnIndex][rowIndex],
          colspan: 1
        };
      } else {
        return {
          rowspan: 0,
          colspan: 1
        };
      }
    }
  }
};
</script>
<style scoped>
.dialog_table {
  min-width: 900px;
  max-width: 1600px;
  margin-top: -5vh;
}
</style>